# -*- coding: utf-8 -*-


import os
import sys

sys.path.append(os.path.abspath(os.path.join(__file__, os.path.pardir, os.path.pardir)))

import logging

from tornado.options import (
    options,
    define,
    parse_command_line,
    define_logging_options
)

from tornado.web import (
    Application,
    RequestHandler,

)
from tornado.log import LogFormatter

from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.httpclient import HTTPClient, AsyncHTTPClient, HTTPResponse
from tornado.concurrent import Future
from tornado.gen import coroutine

from tornado.ioloop import IOLoop

from py_server.py_flask import app

# 定义命令行参数
define(name='port', default=8000, type=int, help='--port=8000')
# 解析命令行参数
parse_command_line()

# 日志
logger = logging.getLogger()


class IndexHandler(RequestHandler):
    @coroutine
    def get(self):
        param = self.get_argument(name='param', default='')
        self.write(chunk=f'hello {param}')
        pass

    pass


def tornado_server():
    """
    HTTP服务端
    curl 'http://127.0.0.1:8000/index?param=world'
    """
    application = Application(handlers=[(r'/index', IndexHandler)])
    application.listen(options.port)
    logger.info(f'0.0.0.0:{options.port}')
    IOLoop.instance().start()

    pass


def tornado_client():
    """
    同步HTTP客户端
    """
    url: str = 'http://127.0.0.1:8000/index?param=world'
    client = HTTPClient()
    response: HTTPResponse = client.fetch(url)
    print(response.body)
    pass


def tornado_async():
    """
    异步HTTP客户端
    """
    url: str = 'http://127.0.0.1:8000/index?param=world'
    # 同步客户端
    client = AsyncHTTPClient()

    def callback_function(response: HTTPResponse):
        print(response.body)
        pass

    # client.fetch(url, callback=callback_function)
    # 版本6.0移除callback参数

    future: Future = Future()
    client.fetch(url).add_done_callback(lambda f: future.set_result(f.result()))
    if future.done():
        print(future.result())
        pass
    pass


async def tornado_async1():
    """
    异步HTTP客户端
    """
    url: str = 'http://127.0.0.1:8000/index?param=world'
    # 同步客户端
    client = AsyncHTTPClient()
    response: HTTPResponse = await client.fetch(url)
    print(response.code, response.body)
    return response.body


def tornado_flask():
    """使用tornado部署flask"""
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(options.port)
    # 多进程不支持Windows
    http_server.start(num_processes=1)
    logger.info(f'0.0.0.0:{options.port}')
    IOLoop.instance().start()
    pass


if __name__ == '__main__':
    # tornado_server()
    # tornado_client()
    # tornado_async()

    IOLoop.instance().run_sync(tornado_async1)

    # tornado_flask()
    pass
